package com.leyou.search.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.SpecParam;
import com.leyou.item.pojo.SpuBo;
import com.leyou.item.pojo.SpuDetail;
import com.leyou.search.clients.BrandClient;
import com.leyou.search.clients.CategoryClient;
import com.leyou.search.clients.GoodsClient;
import com.leyou.search.clients.SpecClient;
import com.leyou.search.pojo.Goods;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class IndexService {

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private SpecClient specClient;

    //把SpuBo转换为Goods的方法
    public Goods buildGoods(SpuBo spuBo) {
        Goods goods = new Goods();
        //拷贝赋值相同的属性
        BeanUtils.copyProperties(spuBo, goods);
        //还有四个字段为空
        // 在 all 里面添加 标题 分类 品牌
        //查询分类
        List<String> names = this.categoryClient.queryNameByIds(Arrays.asList(spuBo.getCid1(), spuBo.getCid2(), spuBo.getCid3()));
        //最后把品牌和分类添加进去
        String all = spuBo.getTitle() + " " + StringUtils.join(names, " ");
        //添加all
        goods.setAll(all);
        // price
        // skus
        List<Sku> skus = this.goodsClient.querySkuBySpuId(spuBo.getId());
        List<Map<String, Object>> skuListMap = new ArrayList<>();
        List<Long> prices = new ArrayList<>();
        skus.forEach(sku -> {
            prices.add(sku.getPrice());
            Map<String, Object> skuMap = new HashMap<>();
            skuMap.put("id", sku.getId());
            skuMap.put("title", sku.getTitle());
            skuMap.put("price", sku.getPrice());
            skuMap.put("image", StringUtils.isBlank(sku.getImages()) ? "" : sku.getImages().split(",")[0]);
            skuListMap.add(skuMap);
        });
        goods.setSkus(JsonUtils.serialize(skuListMap));
        goods.setPrice(prices);
        // specs
        //获取到所有可搜索的规格参数
        List<SpecParam> searcheParams = this.specClient.querySpecParam(null, spuBo.getCid3(), true);
        SpuDetail spuDetail = this.goodsClient.querySpuDetailById(spuBo.getId());
        //通用规格键值对集合map
        Map<Long, Object> genericMap = JsonUtils.nativeRead(spuDetail.getGenericSpec(), new TypeReference<Map<Long, Object>>() {
        });
        //特有规格键值对集合map
        Map<Long, List<String>> specialMap = JsonUtils.nativeRead(spuDetail.getSpecialSpec(), new TypeReference<Map<Long, List<String>>>() {
        });
        Map<String, Object> Specs = new HashMap<>();
        searcheParams.forEach(specParam -> {
            Long id = specParam.getId();
            String name = specParam.getName();
            //通用参数
            Object value = null;
            if (specParam.getGeneric()) {
                //通用参数
                value = genericMap.get(id);
                if (specParam.getNumeric() && null != value) {
                    //数值类型可能需要加分段和单位
                    value = this.chooseSegment(value.toString(), specParam);
                }
            } else {//特有参数
                value = specialMap.get(id);
            }
            if (null == value) {
                value = "其他";
            }
            Specs.put(name, value);
        });
        goods.setSpecs(Specs);
        return goods;
    }


    private String chooseSegment(String value, SpecParam p) {
        double val = NumberUtils.toDouble(value);
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {//segment:1000-2000
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = NumberUtils.toDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = NumberUtils.toDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();//添加单位
                }
                break;
            }
        }
        return result;
    }
}
